package cn.ug.util;

import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author zhaohg
 * @date 2018/07/19.
 */

public class HttpClientUtil {

    private HttpClientUtil() {

    }

    private static final Logger     LOG           = LoggerFactory.getLogger(HttpClientUtil.class);
    private static       HttpClient defaultClient = createHttpClient(200, 20, 5000, 5000, 3000);

    /**
     * 实例化HttpClient
     *
     * @param maxTotal                 连接池最大并发连接数
     * @param maxPerRoute              单路由最大并发数
     * @param socketTimeout            从服务器读取数据的timeout
     * @param connectTimeout           和服务器建立连接的timeout
     * @param connectionRequestTimeout 从连接池获取连接的timeout
     * @return HttpClient
     */
    public static HttpClient createHttpClient(int maxTotal, int maxPerRoute, int socketTimeout, int connectTimeout, int connectionRequestTimeout) {
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout).build();
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(maxTotal);
        cm.setDefaultMaxPerRoute(maxPerRoute);
        return HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(defaultRequestConfig).build();
    }

    /**
     * 发送post请求
     *
     * @param httpClient
     * @param url        请求地址
     * @param params     请求
     * @param encoding   编码
     * @return 请求结果
     */
    public static String sendPost(HttpClient httpClient, String url, Map<String, String> params, Charset encoding) {
        String resp = "";
        HttpPost httpPost = new HttpPost(url);
        if (params != null && params.size() > 0) {
            List<NameValuePair> formParams = new ArrayList<>();
            Iterator<Map.Entry<String, String>> itr = params.entrySet().iterator();
            while (itr.hasNext()) {
                Map.Entry<String, String> entry = itr.next();
                formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(formParams, encoding);
            httpPost.setEntity(postEntity);
        }
        CloseableHttpResponse response = null;
        try {
            response = (CloseableHttpResponse) httpClient.execute(httpPost);
            resp = EntityUtils.toString(response.getEntity(), encoding);
        } catch (IOException e) {
            LOG.warn("发送post请求失败,url={}", url, e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    LOG.warn("关闭response失败", e);
                }
            }
        }
        return resp;
    }

    public static String sendPostJson(String url, String json, Header... headers) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeaders(headers);
        httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
        httpPost.setEntity(new StringEntity(json, Charset.forName("UTF-8")));
        CloseableHttpResponse response = null;
        String resp = "";
        try {
            response = (CloseableHttpResponse) defaultClient.execute(httpPost);
            resp = EntityUtils.toString(response.getEntity(), Charset.forName("utf8"));
        } catch (IOException e) {
            LOG.warn("发送post请求失败,url={}", url, e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    LOG.warn("关闭response失败", e);
                }
            }
        }
        return resp;
    }

    /**
     * 使用默认httpClient发送post请求
     *
     * @param url    请求地址
     * @param params 请求参数
     * @return 请求返回结果
     */
    public static String sendPost(String url, Map<String, String> params) {
        Charset encoding = Charset.forName("utf8");
        return sendPost(defaultClient, url, params, encoding);
    }

    /**
     * 发送get请求
     *
     * @param httpClient
     * @param url        请求地址
     * @param encoding   编码方式
     * @return 响应结果
     * @author zhanglihui
     */
    public static String sendGet(HttpClient httpClient, String url, Charset encoding) {
        HttpGet httpget = new HttpGet(url);
        String resp = "";
        // 执行get请求.
        CloseableHttpResponse response = null;
        try {
            response = (CloseableHttpResponse) httpClient.execute(httpget);
            resp = EntityUtils.toString(response.getEntity(), encoding);
        } catch (IOException e) {
            LOG.warn("发送get请求失败", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    LOG.warn("关闭response失败", e);
                }
            }
        }
        return resp;
    }

    /**
     * 使用默认httpClient发送post请求
     *
     * @param url 请求地址
     * @return 请求返回结果
     */
    public static String sendGet(String url) {
        Charset encoding = Charset.forName("utf8");
        return sendGet(defaultClient, url, encoding);
    }

    public static RequestConfig getTimeoutConfig() {
        return RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(5000).build();
    }

}
